package io.github.flylinran.common.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller层访问记录，方便开发时使用
 */
@Slf4j
@Profile({"dev"})
@Aspect
@Component
public class ControllerLogAspect {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public io.github.flylinran.common.utils.R io.github.flylinran.modules.*.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("接收请求 -> [{}]{} (From -> [{}])", request.getMethod(), request.getRequestURL(), request.getRemoteAddr());
        log.info("处理请求 -> [{}.{}]", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        log.info("前端传参 -> {}", JSON.toJSONString(joinPoint.getArgs()));

        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void doAfterReturning(Object object) {
        log.info("处理时间 -> {}ms", System.currentTimeMillis() - startTime.get());
        log.info("后台响应 -> {}", JSON.toJSONString(object));
        startTime.remove();
    }
}